package com.weedsdream.app.compose

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PointMode
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.luck.picture.lib.entity.LocalMedia
import com.weedsdream.app.R
import com.weedsdream.app.colorplate.curRGB
import com.weedsdream.app.colorplate.emphasizeCurColor
import com.weedsdream.app.compose.ToolType.橡皮擦
import com.weedsdream.app.compose.ToolType.笔
import com.weedsdream.app.compose.ToolType.选择
import com.weedsdream.app.function.fullView
import com.weedsdream.app.struct.Path
import com.weedsdream.app.struct.drafts
import com.weedsdream.compose.Space
import com.weedsdream.function.Toast

/**背景图*/
internal var bgImg by mutableStateOf<LocalMedia?>(null)

/** 橡皮擦位置<可见性、偏移位置>*/
var esrIOft by mutableStateOf(Pair(false, Offset.Zero))

/** 屏幕中心坐标(坐标转换使用)*/
var scCenter by mutableStateOf<Offset?>(null)

/** 画板中心相对屏幕中心偏移值(可组合函数偏移使用)*/
var boxOffset by mutableStateOf(IntOffset.Zero)

/** 画布缩放*/
var boxScale by mutableFloatStateOf(1f)

/**画板入口Ui*/
@Composable
@Preview(widthDp = 600, heightDp = 350)
fun DrawBoardMainUi(test: Boolean = true) {
    Box(Modifier
        .fillMaxSize()
        .onGloballyPositioned { coordinates ->
            if (scCenter == null) {
                scCenter = Offset(coordinates.size.width / 2f, coordinates.size.height / 2f)
            }
        }) {
        //底层画板
        BoardUi()
        //按钮组
        Buttons()
        //取色板按钮组
        if (!hidden) ColorPlateAttachButton({
            when (curTool) {
                笔 -> AttachBtn("全览", R.drawable.drawboard) { fullView() }
                橡皮擦 -> Eraser(test)
                选择 -> ChosenPathBtn(test)
                else -> {}
            }
        }) {
            if (curTool == 选择) if (chosenPaths.isNotEmpty()) ChosenPathContent(test)
        }
        //更多UI开启
        if (moreUiOpen) More(test)
    }
    Toast(test)
}

/**上下蒙版上层绘制的笔迹*/
private val upWriting = mutableStateMapOf<Color, SnapshotStateList<Path>>()

/**纯画板内容*/
@Composable
fun BoardUi() {
    val mod = Modifier
        .fillMaxSize()
        .offset { boxOffset }
        .scale(boxScale)
    //背景
    Box(mod) {
        if (bgImg == null) Icon(
            painterResource(id = R.drawable.center), null,
            Modifier
                .size(15.dp)
                .align(Alignment.Center), Color.Unspecified
        ) else AsyncImage(
            model = bgImg!!.path, contentDescription = null, modifier = Modifier.fillMaxSize()
        )
    }
    //监视相关变量，以便及时更新顶层蒙版笔迹
    Box {
        LaunchedEffect(emphasizeCurColor, curTool) {//强调选中色变化时
            if (curTool == 选择) return@LaunchedEffect
            upWriting.clear()
            if (emphasizeCurColor) drafts[curRGB]?.let { upWriting[curRGB] = it }
        }
        LaunchedEffect(curRGB, drafts[curRGB] == null) { //当前颜色变化时
            if (!emphasizeCurColor || curTool == 选择) return@LaunchedEffect
            upWriting.clear()
            drafts[curRGB]?.let { upWriting[curRGB] = it }
        }
        LaunchedEffect(chosenPaths.size, chosenPaths[curRGB]) {//选择模式选中数量变化时
            upWriting.clear()
            upWriting.putAll(chosenPaths)
        }
    }
    //下层绘图层
    Canvas(mod) {
        for ((color, paths) in drafts) {
            if (upWriting[color] != null && upWriting[color]!!.size == paths.size) continue
            for (path in paths) {
                if (upWriting[color] != null && upWriting[color]!!.contains(path)) continue
                drawPoints(
                    points = path.points, pointMode = PointMode.Polygon, color = color,
                    strokeWidth = path.penSize
                )
            }
        }
    }
    //上下蒙版
    if (emphasizeCurColor || curTool == 选择) Space(Color.LightGray, 0.9f)
    //上层绘图层
    Canvas(mod) {
        for ((color, paths) in upWriting) for (path in paths) {
            drawPoints(
                points = path.points, pointMode = PointMode.Polygon, color = color,
                strokeWidth = path.penSize
            )
        }
    }
    //橡皮擦
    val (ew, eh) = with(LocalDensity.current) {
        Pair(eraserSize.x.toDp() * 2, eraserSize.y.toDp() * 2)
    }
    if (esrIOft.first) Spacer(Modifier
        .size(ew, eh)
        .offset { IntOffset(esrIOft.second.x.toInt(), esrIOft.second.y.toInt()) }
        .alpha(0.5f)
        .background(Color(0xFF0277BD)))
    //手势事件
    BoardSpaceGesture()
}
